/*
 * texture.c
 */

#include <utils/png_utils.h>
#include "texture.h"

#define GAMEVIEW_T_ARRAY_SIZE 20

static struct texture terrain_t_list[GAMEVIEW_T_ARRAY_SIZE];
static struct texture unit_t_list[GAMEVIEW_T_ARRAY_SIZE];
static int terrain_t_size = 0;
static int unit_t_size = 0;
static int texture_initialized = 0;

/*
 * Attempts to load the given filename as a PNG texture and insert the texture
 * into the given slot of the terrain texture array.
 */
int texture_load_terrain( const char *filename, int index ) {
    struct texture t;
    t.id = loadPNGTextureWH( filename, &(t.width), &(t.height) );
    terrain_t_list[index % GAMEVIEW_T_ARRAY_SIZE] = t;
    terrain_t_size++;
    return terrain_t_size - 1;
}

/*
 * Attempts to load the given filename as a PNG texture.
 * Returns the texture ID if successful.
 */
int texture_load_unit( const char *filename ) {
    struct texture t;
    t.id = loadPNGTextureWH( filename, &(t.width), &(t.height) );
    unit_t_list[unit_t_size] = t;
    unit_t_size++;
    return unit_t_size - 1;
}

/*
 * Returns the texture structure located at the given index of the terrain
 * texture array.
 */
struct texture texture_get_terrain( int i ) {
    return terrain_t_list[i];
}

/*
 * Returns the texture structure located at the given index of the unit texture
 * attary.
 */
struct texture texture_get_unit( int i ) {
    return unit_t_list[i];
}

/*
 * Lua hook for the function
 * texture_load_terrain( const char *filename, int index )
 */
int texture_lua_load_terrain( lua_State *L ) {
    const char *filename;
    int index;
    if( lua_gettop(L) < 2 ) {
        lua_pushstring(L, "Too few arguments");
        lua_error(L);
        return 0;
    }
    else {
        filename = lua_tostring(L, 1);
        index = lua_tonumber(L, 2);
        lua_pop(L, 2); /* Clear stack */
        texture_load_terrain(filename, index);
        return 0;
    }
}

/*
 * Calls the Lua function "loadTextures", which should load all the textures
 * used as terrain.
 */
void texture_load_textures() {
    luaR_fcall("loadTextures");
}

/*
 * Initialize the texture module. Attempts to load and execute the Lua script
 * located at "scripts/texture.lua".
 */
int texture_init() {
    if( texture_initialized ) {
        /* TODO: warning */
        return 1;
    }
    else {
        luaR_package_create();
        luaR_package_add("loadTerrainTexture", texture_lua_load_terrain);
        /*luaR_package_add("loadUnitTexture", texture_lua_load_unit);*/
        luaR_package_set("RG_texture");
        luaR_load_file("scripts/texture.lua");
        texture_initialized = 1;
        return 0;
    }
}
